<?php
if (session_id() == '') {
    session_start();
}
require_once ('../utility/appConsts.php');
/**
 * Login class that manages user authentication with Server
 * 
 * @author relsellglobal
 *        
 */
class Login {
	var $loginresult = '';
	var $loggedIn = '';
	var $loggedInUserId = '';
	var $loggedInUserType = '';
	function performLogin($userName, $password) {
		$appConstants = new appConstsClass ();
		$appConstants->initialize ();
		$arr = array ();
		$db_handle = mysql_connect ( $appConstants->SERVER, $appConstants->DBUSERNAME, $appConstants->DBPASSWORD );
		$db_found = mysql_select_db ( $appConstants->DBNAME, $db_handle );
		$error_result = mysql_error ();
		if ($error_result) {
			$arr ['error'] = $appConstants->DB_CONNECTION_FAILURE;
			return $arr;
		}
		if ($db_found) {
			$SQL = "SELECT id,password,user_type FROM login_table where username='$userName'";
			$result = mysql_query ( $SQL, $db_handle );
			$total = mysql_num_rows ( $result );
			if ($total > 0) {
				while ( $db_field = mysql_fetch_assoc ( $result ) ) {
					if ($password == $db_field ['password']) {
						$loginresult = $appConstants->LOGIN_SUCCESS;
						$loggedIn = 'true';
						$loggedInUserId = $db_field ['id'];
						$loggedInUserType = $db_field ['user_type'];
						if ($appConstants->DEBUG) {
							echo 'login done' . "<br/>";
						}
						break;
					} else {
						$loginresult = $appConstants->LOGIN_FAILURE;
						$loggedIn = 'false';
						$loggedInUserId = 'no value';
						$loggedInUserType = 'no type';
						if ($appConstants->DEBUG) {
							echo 'login unsuccessful' . "<br/>";
						}
						break;
					}
				}
				mysql_close ( $db_handle );
			}
			$arr ['loginresult'] = $loginresult;
			$arr ['loggedIn'] = $loggedIn;
			$arr ['loggedInUserId'] = $loggedInUserId;
			$arr ['loggedInUserType'] = $loggedInUserType;
			$arr ['error'] = $loggedIn;
			return $arr;
		}
	}
	function performUserRegistration($username, $password, $email) {
		$appConstants = new appConstsClass ();
		$appConstants->initialize ();
		$arr = array ();
		$db_handle = mysql_connect ( $appConstants->SERVER, $appConstants->DBUSERNAME, $appConstants->DBPASSWORD );
		$db_found = mysql_select_db ( $appConstants->DBNAME, $db_handle );
		if ($db_found) {
			$SQL = "INSERT INTO login_table (username ,password,emailid) VALUES ('$username','$password','$email') ";
			if ($appConstants->DEBUG) {
				echo $SQL . "<br/>";
			}
			mysql_query ( $SQL );
			$res = null;
			
			$res = mysql_error ( $db_handle );
			if ($res != null) {
				if ($appConstants->DEBUG) {
					echo $res . "<br/>";
				}
				$arr ['error'] = $appConstants->USERALREADY;
			}
			if (! $res && $appConstants->DEBUG) {
				$res1 = mysql_affected_rows ();
				echo $res1 == 1 ? $res1 . "<br/>" : 'no value';
			}
			$arr ['error'] = $appConstants->USERREGISTEREDSUCCESS;
			return $arr;
		}
	}
}
?>